

package com.kimo.shop.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.kimo.shop.bean.dto.AreaDto;
import com.kimo.shop.bean.enums.AreaLevelEnum;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.kimo.shop.common.util.PageParam;
import com.kimo.shop.bean.model.Area;
import com.kimo.shop.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * @author kimo-taozhouchuan on 2018/10/26.
 */
@RestController
@RequestMapping("/admin/area")
public class AreaController {

    @Autowired
    private AreaService areaService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('admin:area:page')")
    public ResponseEntity<IPage<Area>> page(Area area,PageParam<Area> page) {
        IPage<Area> sysUserPage = areaService.page(page, new LambdaQueryWrapper<Area>());
        return ResponseEntity.ok(sysUserPage);
    }

    /**
     * 获取省市
     */
    @GetMapping("/list")
    @PreAuthorize("@pms.hasPermission('admin:area:list')")
    public ResponseEntity<List<Area>> list(Area area) {
        List<Area> areas = areaService.list(new LambdaQueryWrapper<Area>()
                .like(area.getAreaName() != null, Area::getAreaName, area.getAreaName())
                .le(Objects.nonNull(area.getMaxLevel()), Area::getLevel, area.getMaxLevel())
        );
        return ResponseEntity.ok(areas);
    }

    /**
     * 通过父级id获取区域列表
     */
    @GetMapping("/listByPid")
    public ResponseEntity<List<Area>> listByPid(Long pid) {
        List<Area> list = areaService.listByPid(pid);
        return ResponseEntity.ok(list);
    }

    /**
     * 获取信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@pms.hasPermission('admin:area:info')")
    public ResponseEntity<Area> info(@PathVariable("id") Long id) {
        Area area = areaService.getById(id);
        return ResponseEntity.ok(area);
    }

    /**
     * 保存
     */
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin:area:save')")
    public ResponseEntity<Void> save(@Valid @RequestBody Area area) {
        if (area.getParentId() != null && !Objects.equals(area.getParentId(), 0L)) {
            Area parentArea = areaService.getById(area.getParentId());
            area.setLevel(parentArea.getLevel() + 1);
            areaService.removeAreaCacheByParentId(area.getParentId());
            // 因为获取地址的时候，过滤掉了没有三级地址的一级地址，情况缓存的时候，一级地址也需要清空一下
            if (Objects.equals(area.getLevel(), AreaLevelEnum.THIRD_LEVEL.value())) {
                areaService.removeAreaCacheByParentId(0L);
            }
        }
        hasSameName(area);
        areaService.save(area);
        areaService.removeAreaListCache();
        return ResponseEntity.ok().build();
    }

    /**
     * 修改
     */
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin:area:update')")
    public ResponseEntity<Void> update(@Valid @RequestBody Area area) {
        hasSameName(area);
        areaService.updateById(area);
        areaService.removeAreaListCache();
        areaService.removeAreaCacheByParentId(area.getParentId());
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('admin:area:delete')")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        if (areaService.count(new LambdaQueryWrapper<Area>().eq(Area::getParentId,id)) > 0) {
            // 请先删除子地区
            throw new KimoShopBindException("kimo.area.delete");
        }

        Area area = areaService.getById(id);
        areaService.removeById(id);
        areaService.removeAreaListCache();
        areaService.removeAreaCacheByParentId(area.getParentId());
        // 因为获取地址的时候，过滤掉了没有三级地址的一级地址，情况缓存的时候，一级地址也需要清空一下
        if (Objects.equals(area.getLevel(), AreaLevelEnum.THIRD_LEVEL.value())) {
            areaService.removeAreaCacheByParentId(0L);
        }
        return ResponseEntity.ok().build();
    }

    /**
     * 获取省市信息
     */
    @GetMapping("/areaListInfo")
    public ResponseEntity<List<AreaDto>> getAreaListInfo() {
        return ResponseEntity.ok(areaService.getAreaListInfo());
    }

    private void hasSameName(Area area) {
        int count = areaService.count(new LambdaQueryWrapper<Area>()
                .eq(Area::getParentId, area.getParentId())
                .eq(Area::getAreaName, area.getAreaName())
                .ne(Objects.nonNull(area.getAreaId()) && !Objects.equals(area.getAreaId(), Constant.ZERO_LONG), Area::getAreaId, area.getAreaId())
        );
        if (count > 0) {
            throw new KimoShopBindException("该地区已存在");
        }
    }
}
